package com.samoiloff.ui.btns {
	import flash.display.MovieClip;
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;

	/**
	 * @author Damirr
	 */
	public class BtnController extends EventDispatcher {
		
		protected var _mc: MovieClip;
		private var _enabled:Boolean;
		
		public function BtnController(mc:MovieClip) {
			_mc = mc.hitMc ? mc.hitMc : mc;
			
			_mc.useHandCursor = _mc.buttonMode = true;//			_mc.useHandCursor = _mc.buttonMode = false;
			
			_mc.addEventListener(MouseEvent.ROLL_OVER, onMouseOver);
			_mc.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
			_mc.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
			_mc.addEventListener(MouseEvent.ROLL_OUT, onMouseOut);
			_mc.addEventListener(MouseEvent.CLICK, onClick);
			
			onMouseOut();
			
		}
		
		public function destroy():void {
			_mc.removeEventListener(MouseEvent.ROLL_OVER, onMouseOver);
			_mc.removeEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
			_mc.removeEventListener(MouseEvent.MOUSE_UP, onMouseUp);
			_mc.removeEventListener(MouseEvent.ROLL_OUT, onMouseOut);
			_mc.removeEventListener(MouseEvent.CLICK, onClick);
			
			_mc = null;
		}
		
		private function onMouseUp(e: MouseEvent): void {
			onMouseOver();
			dispatchEvent(e);
		}
				
		private function onMouseDown(e: MouseEvent): void {
			_mc.gotoAndStop(3);
			dispatchEvent(e);
		}
			
		private function onMouseOver(e: MouseEvent = null): void {
			_mc.gotoAndStop(2);
			if (e) {
				dispatchEvent(e);
			}
		}

		private function onMouseOut(e: MouseEvent = null): void {
			_mc.gotoAndStop(1);
			if (e) {
				dispatchEvent(e);
			}
		}
		
		public function get enabled():Boolean {
			return _enabled;
		}
		
		public function set enabled(enabled:Boolean):void {
			_enabled = enabled;
			_mc.mouseEnabled = _mc.mouseChildren = _enabled;
			_mc.gotoAndStop(_enabled ? 1 : 4);
		}
		
		private function onClick(e: MouseEvent): void {
			onMouseOver();
			dispatchEvent(e);
		}
		
		
		public function get mc(): MovieClip {
			return _mc;
		}
		
	}
}
